<script setup>
import api from '@/api'
import { Message } from '@arco-design/web-vue'
import { ref, reactive, watch, nextTick, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import UploadFile from '@/components/uploadFile.vue'
import UploadImage from '@/components/uploadImage.vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'

const $route = useRoute()
const $router = useRouter()
const title = ref('')

// 招聘人员搜索
const keyword = ref('')
const status = ref('')

// 招聘人员列表
const userLists = ref([])

// 招聘人员状态列表
const StatusList = ref([])

// 部门数据
const departments = ref([])

// 岗位数据
const posts = ref([])

// 招聘详情
const form = reactive({
  departments: '',
  departments_id: '',
  posts: '',
  posts_id: '',
  post_ask: '',
  recruit_number: '',
  // muban: '',
  admission_number: '',
  interview_number: '',
})

// const formRules = {
//   departments_id: [
//     {
//       required: true,
//       message: '请选择部门',
//     }
//   ],
//   posts_id: [
//     {
//       required: true,
//       message: '请选择岗位',
//     }
//   ],
//   recruit_number: [
//     {
//       required: true,
//       message: '请输入招聘人数',
//     },
//     {
//       type: 'number',
//       min: 1,
//       message: '招聘人数不能小于1人',
//     }
//   ],
//   post_ask: [
//     {
//       required: true,
//       message: '请输入岗位要求',
//     }
//   ],
//   admission_number: [
//     {
//       required: true,
//       message: '请输入录取人数',
//     },
//     {
//       type: 'number',
//       message: '录取人数必须为数字',
//     }
//   ],
//   interview_number: [
//     {
//       required: true,
//       message: '请输入面试人数',
//     },
//     {
//       type: 'number',
//       message: '面试人数必须为数字',
//     }
//   ]
// }

// 招聘模板
const templates = ref([])

// const addSon = (rowIndex) => {
//   data.value[rowIndex].son.push({
//     wenti: '问题2',
//     yaodian: '要点1',
//     putong: 1,
//     lianghao: 3,
//     youxiu: 5,
//   })
// }

// const deleteSon = (rowIndex, index) => {
//   data.value[rowIndex].son.splice(index, 1)
// }

// const addItem = () => {
//   data.value.push({
//     bankuai: '',
//     son: [
//       {
//         wenti: '',
//         yaodian: '',
//         putong: 1,
//         lianghao: 3,
//         youxiu: 5,
//       },
//     ],
//   })
// }

// const deleteItem = (rowIndex) => {
//   data.value.splice(rowIndex, 1)
// }

const toJump = (url) => {
  console.log('router', $router.push(url))
  $router.push(url)
}

// const handleSubmit = (data) => {
//   console.log(data)
// }

const visible = ref(false)
const form1 = reactive({
  name: '',
  mobile: '',
  email: '',
  biographical_notes: '',
  channel: '',
})

const form1Rules = {
  name: [
    {
      required: true,
      message: '请输入姓名',
    },
  ],
  // mobile: [
  //   {
  //     required: true,
  //     message: '请输入手机号',
  //   },
  //   {
  //     pattern: /^1[3-9]\d{9}$/,
  //     message: '请输入正确的手机号',
  //   },
  // ],
  // email: [
  //   {
  //     required: true,
  //     message: '请输入邮箱',
  //   },
  //   {
  //     type: 'email',
  //     message: '请输入正确的邮箱',
  //   },
  // ],
  // biographical_notes: [
  //   {
  //     required: true,
  //     message: '请上传简历',
  //   },
  // ],
}

const form1Ref = ref(null)

const handleForm1Submit = async () => {
  console.log('新增招聘人员')
  form1Ref.value.validate(async (vaild) => {
    const formData = {
      name: form1.name,
      mobile: form1.mobile,
      email: form1.email,
      channel: form1.channel,
      biographical_notes: form1.biographical_notes,
      recuit_plan_id: $route.query.id,
      image: form1.image,
    }
    const res = await api.post('/recruit/createApplication', formData)
    if (res.code == 200) {
      Message.success('提交成功')
      visible.value = false
      getYingpinUsers()
    } else {
      Message.error(res.message)
    }
  })
}

// const handleClick = () => {
//   visible.value = true
// }
// const handleBeforeOk = (done) => {
//   console.log(form)
//   window.setTimeout(() => {
//     done()
//     // prevent close
//     // done(false)
//   }, 3000)
// }
const handleCancel = () => {
  visible.value = false
}

// 停止招聘
const stopRecruit = async () => {
  console.log('停止招聘')
  const res = await api.get(`/recruit/recruitEnds?plan_id=${$route.query.id}`)
  if (res.code == 200) {
    Message.success('已停止招聘')
    toJump('/recruit/plans/index')
  } else {
    Message.error(res.message)
  }
}

const getUserStatusList = async () => {
  const res = await api.get(
    `/recruit/statusList?recuit_plan_id=${$route.query.id}`
  )
  StatusList.value = res.data
}

// // 保存修改
// const savePlans = async () => {
//   console.log('保存招聘计划', form)
//   const formData = {
//     departments_id: form.departments_id,
//     posts_id: form.posts_id,
//     recruit_number: form.recruit_number,
//     post_ask: form.post_ask,
//     recruit_template_id: '',
//     plan_id: $route.query.id
//   }
//   let url = '/recruit/updatePlan'
//   const res = await api.post(url, form)
//   if (res.code == 200) {
//     Message.success('保存成功')
//     toJump('/recruit/plans/index')
//   } else {
//     Message.error(res.message)
//   }
// }

// 获取招聘计划详情
const getDetail = async () => {
  console.log('获取招聘计划详情', form)
  const res = await api.get(
    `/recruit/recruitPlanDetails?plan_id=${$route.query.id}`
  )
  // form = reactive(res.data)
  form.id = res.data.id
  form.departments_id = res.data.departments_id
  form.departments = res.data.departments
  form.posts = res.data.posts
  form.posts_id = res.data.posts_id
  form.post_ask = res.data.post_ask
  form.recruit_number = res.data.recruit_number + ''
  form.admission_number = res.data.admission_number + ''
  form.residue_number = res.data.residue_number + ''
  form.interview_number = res.data.interview_number + ''

  console.log('form', form)
}

// 获取计划关联的招聘模板
const getRecruitTemplate = async () => {
  const res = await api.get(
    `/recruit/planTemplateDetails?plan_id=${$route.query.id}`
  )
  templates.value = res.data
}

// 获取招聘人员列表
const getYingpinUsers = async () => {
  console.log('获取招聘人员列表')
  const res = await api.get(
    `/recruit/applicationList?keyword=${keyword.value}&status=${status.value}&recuit_plan_id=${$route.query.id}`
  )
  userLists.value = res.data
}

// 部门列表
const getDepartments = async () => {
  console.log('获取部门列表')
  const res = await api.get('/recruit/departmentsList')
  departments.value = res.data
  if (res.data.length > 0) {
    getPosts(res.data[0].id)
  }
}

// 岗位列表
const getPosts = async (departId) => {
  console.log('获取岗位列表' + departId)
  const res = await api.get(`/recruit/postsList?department_id=${departId}`)
  posts.value = res.data
}

const init = async () => {
  console.log('加载收据')
  getUserStatusList()
  await getDepartments()
  // 获取详情和招聘人员列表
  getDetail()
  getRecruitTemplate()
  getYingpinUsers()
}

watch(
  () => form.departments_id,
  (newVal) => {
    console.log('change departments_id', newVal)
    posts.value = []
    // form.posts_id = ''
    getPosts(newVal)
  }
)

init()

const handleUpload = (file, fileList) => {
  console.log('upload file', file, fileList)
  form1.biographical_notes = file
}
</script>

<template>
  <div class="page">
    <div class="header">招聘计划详情</div>

    <div class="record_body" style="padding: 20px 24px 0">
      <div class="form_body">
        <div class="flex at_c jc_b mb20">
          <div class="form_body_title">招聘信息</div>
          <a-space>
            <a-button
              v-if="!userLists.length"
              @click="
                toJump('/recruit/plans/addPlans?plan_id=' + $route.query.id)
              "
              type="primary"
              >修改</a-button
            >
            <a-button @click="stopRecruit" type="primary" status="danger"
              >招聘结束</a-button
            >
          </a-space>
        </div>

        <a-form auto-label-width :model="form">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="departments_id" label="所属部门">
                <!-- <a-select readonly v-model="form.departments_id"
                          placeholder="请选择招聘部门"
                          allow-clear>
                  <a-option v-for="(item, index) in departments" :key="index" :value="item.id">{{ item.name }}</a-option>
                </a-select> -->
                <a-input readonly v-model="form.departments"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="posts_id" label="岗位名称">
                <!-- <a-select readonly v-model="form.posts_id"
                          placeholder="请选择招聘岗位名称"
                          allow-clear>
                  <a-option v-for="(item, index) in posts" :key="index" :value="item.id">{{ item.name }}</a-option>
                </a-select> -->
                <a-input readonly v-model="form.posts"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="post_ask" label="岗位要求">
                <a-textarea
                  readonly
                  v-model="form.post_ask"
                  placeholder="请输入岗位要求"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="interview_number" label="面试轮数">
                <a-input
                  readonly
                  v-model="form.interview_number"
                  placeholder="请输入面试轮数"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="muban" label="招聘模板">
                <a-button
                  @click="
                    toJump(
                      '/recruit/plans/recruitTemplate?plan_id=' +
                        $route.query.id
                    )
                  "
                  type="primary"
                  >查看详情</a-button
                >
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="recruit_number" label="招聘需求数量">
                <a-input
                  readonly
                  v-model="form.recruit_number"
                  placeholder="请输入招聘需求数量"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="admission_number" label="已录取数量">
                <a-input
                  readonly
                  v-model="form.admission_number"
                  placeholder="请输入已录取数量"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="residue_number" label="当前剩余数量">
                <a-input
                  readonly
                  v-model="form.residue_number"
                  placeholder="请输入当前剩余数量"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>

    <a-divider />

    <div class="record_body" style="padding: 0 24px 20px">
      <div class="form_body">
        <div class="flex at_c jc_b mb20">
          <a-space>
            <a-button @click="visible = true" type="primary"
              >新增应聘人员</a-button
            >
            <a-button
              @click="
                toJump(
                  '/recruit/talentPool/contrast?plan_id=' + $route.query.id
                )
              "
              type="primary"
              >人才对比</a-button
            >
          </a-space>
          <a-space>
            <a-select v-model="status" placeholder="筛选状态">
              <a-option value="">选择状态</a-option>
              <a-option
                v-for="item in StatusList"
                :value="item.value"
                :key="item.value"
                >{{ item.name }}</a-option
              >
            </a-select>
            <a-input-search
              :style="{ width: '320px' }"
              v-model="keyword"
              placeholder="姓名名称模糊查询"
              button-text="查询"
              @search="getYingpinUsers"
              search-button
            />
          </a-space>
        </div>

        <a-table
          :data="userLists"
          :pagination="false"
          :bordered="{ headerCell: true, cell: true }"
        >
          <template #columns>
            <a-table-column title="序号" align="center" :width="80">
              <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
            </a-table-column>
            <a-table-column title="应聘人员" align="center" data-index="name">
            </a-table-column>
            <a-table-column
              title="渠道"
              align="center"
              data-index="channel"
            ></a-table-column>
            <a-table-column
              :filterable="{
                filters: [
                  {
                    text: '已上传',
                    value: '已上传',
                  },
                  {
                    text: '未上传',
                    value: '未上传',
                  },
                ],
                filter: (value, row) => row.is_introduce.includes(value),
              }"
              title="简历是否上传"
              align="center"
              data-index="is_introduce"
            >
              <template #cell="{ record }">
                <div class="diytd">
                  <template v-if="record.is_introduce == '已上传'"
                    >已上传</template
                  >
                  <template v-else>未上传</template>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="面试记录">
              <a-table-column
                title="预约面试时间"
                align="center"
                data-index="reservation_time"
              >
                <template #cell="{ record }">
                  <div
                    class="diytd"
                    v-for="(item, index) in record.record"
                    :key="index"
                  >
                    <div class="h32 jc_c">{{ item.reservation_time }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                title="实际面试时间"
                align="center"
                data-index="interview_time"
              >
                <template #cell="{ record }">
                  <div
                    class="diytd"
                    v-for="(item, index) in record.record"
                    :key="index"
                  >
                    <div class="h32 jc_c">{{ item.interview_time }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                title="面试人"
                align="center"
                data-index="interview_worker"
              >
                <template #cell="{ record }">
                  <div
                    class="diytd"
                    v-for="(item, index) in record.record"
                    :key="index"
                  >
                    <div class="h32 jc_c">{{ item.interview_worker }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="得分" align="center" data-index="score">
                <template #cell="{ record }">
                  <div
                    class="diytd"
                    v-for="(item, index) in record.record"
                    :key="index"
                  >
                    <div class="h32 jc_c">{{ item.score }}</div>
                  </div>
                </template>
              </a-table-column>
            </a-table-column>
            <a-table-column
              title="合计得分"
              align="center"
              data-index="allScore"
            >
            </a-table-column>
            <a-table-column
              :filterable="{
                filters: StatusList.map((item) => {
                  item.text = item.name
                  item.value = item.name
                  return item
                }),
                filter: (value, row) => row.status.includes(value),
              }"
              title="当前状态"
              align="center"
              data-index="status"
            >
            </a-table-column>
            <a-table-column title="查看详情" align="center" :width="100">
              <template #cell="{ record, rowIndex }">
                <div class="diytd">
                  <div class="h32">
                    <a-space>
                      <a-button
                        type="primary"
                        size="mini"
                        @click="
                          toJump(
                            '/recruit/plans/configuration?id=' +
                              record.id +
                              '&plan_id=' +
                              $route.query.id
                          )
                        "
                        >面试配置</a-button
                      >
                      <a-button
                        type="primary"
                        size="mini"
                        @click="
                          toJump(
                            '/recruit/talentPool/recordDetails?id=' +
                              record.id +
                              '&plan_id=' +
                              $route.query.id
                          )
                        "
                        >面试记录</a-button
                      >
                    </a-space>
                  </div>
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      v-model:visible="visible"
      title="新增应聘人员"
      @cancel="handleCancel"
      :footer="false"
    >
      <a-form
        ref="form1Ref"
        :model="form1"
        :rules="form1Rules"
        @submit="handleForm1Submit"
      >
        <a-form-item field="name" label="应聘者姓名">
          <a-input v-model="form1.name" placeholder="请输入应聘者姓名" />
        </a-form-item>
        <a-form-item field="mobile" label="联系电话">
          <a-input v-model="form1.mobile" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item
          field="image"
          label="图像"
          help="请上传jpg、png、gif格式图片、文件大小不能超过1MB"
          validate-trigger="input"
        >
          <uploadImage
            v-model="form1.image"
            width="100px"
            height="100px"
          ></uploadImage>
        </a-form-item>
        <a-form-item field="biographical_notes" label="上传简历">
          <UploadFile
            dir="plans/biographical_notes"
            :maxSize="1"
            @change="handleUpload"
            :accepts="[
              '.doc',
              '.docx',
              '.pdf',
              'image/*',
              'image/jpeg',
              'image/png',
              'image/jpg',
              'application/pdf',
              'application/msword',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            ]"
          />
        </a-form-item>
        <a-form-item v-if="form1.biographical_notes">
          <!-- 超出换行 -->
          <a-row style="display: block; width: 100%; word-break: break-all">{{
            form1.biographical_notes
          }}</a-row>
        </a-form-item>
        <a-form-item field="email" label="联系邮箱">
          <a-input v-model="form1.email" placeholder="请输入联系邮箱" />
        </a-form-item>
        <a-form-item field="channel" label="渠道">
          <a-input v-model="form1.channel" placeholder="请输入渠道" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" status="danger" @click="visible = false"
              >取消</a-button
            >
            <a-button type="primary" @click="handleForm1Submit">提交</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 95%;
  border-bottom: 0;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

:deep(.arco-table-cell):has(.diytd) {
  padding: 0;
}
:deep(.arco-table-cell):has(.diytd) .diytd {
  padding: 0.6rem 1.06667rem;
  border-bottom: 1px solid #ddd;
}
:deep(.arco-table-cell):has(.diytd) .diytd:last-child {
  border: none;
}

.h32 {
  height: 32px;
  display: flex;
  align-items: center;
}

.record_body {
  box-sizing: border-box;
  padding: 20px 24px;
}

.form_body {
  box-sizing: border-box;
  padding: 20px 24px;
  background-color: #fff;
  margin-bottom: 20px;
}

.form_body_title {
  font-size: 18px;
  font-weight: bold;
}
</style>
